/**
 * 
 */
package t4j.polymorphism;

/**
 * @author sz
 *
 * create time：2012-9-5
 */
class Shared{
	
	private int refcount = 0;
	private static long counter = 0;
	private final long id = counter++;
	
	public Shared(){
		System.out.println("Creting" + this);
	}
	
	public void addRef(){refcount++;};
	protected void dispose(){
		if(--refcount == 0)
			System.out.println("Disposing" + this);
	}
	
	public String toString(){return "Shard" + id;}
}

class Composing{
	private Shared shared;
	private static long counter = 0;
	private final long id = counter++;
	
	public Composing(Shared shared){
		System.out.println("Creating" + this);
		this.shared = shared;
		this.shared.addRef();
	}
	
	protected void dispose(){
		System.out.println("disposing" + this);
		shared.dispose();
	}
	
	public String toString(){return "Composing" + id;}
}


public class ReferenceCounting {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Shared shard = new Shared();
		
		Composing[] composing =  {new Composing(shard),new Composing(shard),new Composing(shard)
		,new Composing(shard),new Composing(shard)};
		
		for(Composing c : composing)
			c.dispose();
	}

}
